package com.jyxd.web.controller.basic;

import cn.hutool.core.date.DateUtil;
import com.jyxd.web.data.basic.NursingTask;
import com.jyxd.web.data.common.Result;
import com.jyxd.web.data.dictionary.FrequencyDictionary;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.mq.NursingTaskExecuteSender;
import com.jyxd.web.mq.NursingTaskSender;
import com.jyxd.web.service.assessment.basic.FrequencyDictionaryService;
import com.jyxd.web.service.assessment.basic.NursingTaskService;
import com.jyxd.web.service.patient.PatientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/nursingTask")
public class NursingTaskController {
    private final Logger logger = LoggerFactory.getLogger(NursingTaskController.class);
    @Autowired
    private NursingTaskService nursingTaskService;

    @Autowired
    private NursingTaskSender nursingTaskSender;
    @Autowired
    private FrequencyDictionaryService frequencyDictionaryService;
    @Autowired
    private NursingTaskExecuteSender nursingTaskExecuteSender;
    @Autowired
    private PatientService patientService;

    @GetMapping("/{patientId}")
    public Result<?> queryByPatientId(@PathVariable("patientId") String patientId) {
        return Result.succeed(nursingTaskService.queryByPatientId(patientId));
    }

    @PostMapping("/{patientId}")
    public Result<?> save(@PathVariable("patientId") String patientId, @RequestBody List<NursingTask> nursingTaskList) {
        List<NursingTask> currentNursingTaskList = nursingTaskService.queryByPatientId(patientId);
        Map<String, NursingTask> nursingTaskMap = currentNursingTaskList
                .stream().collect(Collectors.toMap(NursingTask::uniqueId, task -> {
                    // -1 数据库标识符 数据失效
                    task.setStatus(-1);
                    // -1 内存表述,默认数据都有变动
                    task.setDataChangeStatus(-1);
                    return task;
                }));

        for (NursingTask nursingTask : nursingTaskList) {
            if (nursingTaskMap.containsKey(nursingTask.uniqueId())) { //uniqueId 为3字段合并组成唯一key
                NursingTask current = nursingTaskMap.get(nursingTask.uniqueId());
                //新旧数据有变化,旧数据作废,插入新数据
                if (!current.getStartTime().equals(nursingTask.getStartTime()) || //开始时间变化
                        !current.getFrequencyId().equalsIgnoreCase(nursingTask.getFrequencyId())) { //护理频次变化
                    nursingTask.setDataChangeStatus(1);
                } else {
                    //数据没有变动,则不做处理,这里正常不需要设置setStatus(0),
                    //因为DataChangeStatus为0不更改数据
                    current.setStatus(0);
                    current.setDataChangeStatus(0);
                }
            } else {
                //需要新增数据
                nursingTask.setDataChangeStatus(1);
            }
            nursingTask.setStatus(0);
        }

        //需要更新数据
        nursingTaskService.updateBatchById(currentNursingTaskList.stream().filter(nursingTask -> nursingTask.getDataChangeStatus() == -1)
                .peek(nursingTask -> {
                    nursingTask.setDiscardReason("患者更新频次信息");
                    nursingTask.setDiscardTime(new Date());
                }).collect(Collectors.toList()));
        Patient patient = patientService.queryData(patientId);
        //需要插入数据
        List<NursingTask> insertData = nursingTaskList.stream().filter(nursingTask -> nursingTask.getDataChangeStatus() == 1)
                .collect(Collectors.toList());
        nursingTaskService.saveBatch(insertData);
        Map<String, Long> frequencyDict = frequencyDictionaryService.list().stream().collect(Collectors.toMap(FrequencyDictionary::getId, FrequencyDictionary::getDuration));
        for (NursingTask task : insertData) {
            Long dictDuration = frequencyDict.get(task.getFrequencyId());
            if (dictDuration == null || dictDuration == 0L) continue;
            task.setFrequencyDuration(dictDuration);
            long startTimestamp = task.getStartTime().getTime();
            long currentTimestamp = new Date().getTime();
            long duration = currentTimestamp - startTimestamp;
            //开始时间小于当前时间,需要补录数据
            if (duration > 0) {
                startTimestamp = nursingTaskService.repairNursingTask(patient,task, task.getStartTime(), new Date());
                duration = new Date().getTime() - startTimestamp;
            }
            Date nextExecuteDateTime = new Date(startTimestamp);
            task.setNextExecuteTime(nextExecuteDateTime);
            logger.info("间隔:{},下次执行时间:{}", duration, DateUtil.formatDateTime(nextExecuteDateTime));
            nursingTaskSender.send(task, Math.abs(duration));
        }
        return Result.succeed("数据保存成功");
    }
}
